import * as productApi from "../../api/product_manage";
import { SUCCESS_CODE, FETCH_PRODUCT_LIST_FAILED } from "../../config/config";

const FETCH_PRODUCT_LIST = "FETCH_PRODUCT_LIST";
const UPDATE_PRODUCT_CATALOGUE = "UPDATE_PRODUCT_CATALOGUE";
const productManage = {
  namespaced: true,
  state: {
    selected: {},
    productCatalogue: [],
    search: {
      productId: "",
      name: "",
      audit: ""
    },
    productList: []
  },
  mutations: {
    [FETCH_PRODUCT_LIST](state, productList) {
      state.productList = productList;
    },
    [UPDATE_PRODUCT_CATALOGUE](state, productCatalogue) {
      state.productCatalogue = productCatalogue;
    }
  },
  actions: {
    async fetchProductList({ commit, state }) {
      let data = await productApi.fetchProductList();
      return new Promise((resolve, reject) => {
        if (data.data.status === SUCCESS_CODE) {
          let productList = data.data.data;
          let productCatalogueIds = [
            ...new Set(
              productList.map(p => p["catalogId"] + "#$#$" + p["catalogName"])
            )
          ];
          let productCatalogue = productCatalogueIds.map(id =>
            id.split("#$#$")
          );
          commit(UPDATE_PRODUCT_CATALOGUE, productCatalogue);
          commit(FETCH_PRODUCT_LIST, productList);
          resolve(true);
        } else {
          reject(new Error(FETCH_PRODUCT_LIST_FAILED));
        }
      });
    },
    async updateProduct({ commit, state }, product) {
      let respData = await productApi.updateProduct(product);
      respData = respData.data;
      return new Promise(resolve => {
        resolve(respData);
      });
    },
    async newProduct({ commit, state }, product) {
      let respData = await productApi.newProduct(product);
      respData = respData.data;
      return new Promise(resolve => {
        resolve(respData);
      });
    },
    async setSaleStatus({ commit }, updateObj) {
      let respData = await productApi.setSaleStatus(updateObj);
      respData = respData.data;
      return new Promise(resolve => {
        resolve(respData);
      });
    }
  }
};

export default productManage;
